package aviator.test01;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.googlecode.aviator.AviatorEvaluator;
import org.junit.Test;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static org.junit.Assert.assertEquals;


public class VariableExample {
  public static class Bar {
    public Bar() {
      this.name = "bar";
    }


    public String getName() {
      return this.name;
    }


    public void setName(final String name) {
      this.name = name;
    }

    private String name;

  }

  public static class Foo {

    public Bar[] getBars() {
      return this.bars;
    }


    public void setBars(final Bar[] bars) {
      this.bars = bars;
    }

    int i;
    float f;
    Date date = new Date();
    Bar[] bars = new Bar[1];


    public Foo(final int i, final float f, final Date date) {
      super();
      this.i = i;
      this.f = f;
      this.date = date;
      this.bars[0] = new Bar();
    }


    public int getI() {
      return this.i;
    }


    public void setI(final int i) {
      this.i = i;
    }


    public float getF() {
      return this.f;
    }


    public void setF(final float f) {
      this.f = f;
    }


    public Date getDate() {
      return this.date;
    }


    public void setDate(final Date date) {
      this.date = date;
    }

  }


  public static void main(final String[] args) {
    Foo foo = new Foo(100, 3.14f, new Date());
    Map<String, Object> env2 = AviatorEvaluator.newEnv("foo", foo);
    Map<String, Object> env = JSONObject.parseObject(JSON.toJSONString(foo), Map.class);
    // Syntax suger for nested variable access.
    String exp =
            "bars.array[0].name";
    Object result = AviatorEvaluator.execute(exp, env);
    System.out.println("Result: " + result);

  }

  @Test
  public void testQuoteVar() {
    Foo foo = new Foo(100, 3.14f, new Date());
    Map<String, Object> env = new HashMap<String, Object>();
    env.put("foo", foo);
    System.out.println(AviatorEvaluator.execute("#foo.bars[0].name", env));
  }

}
